package net.didactylos.helpline.action;

import net.didactylos.helpline.data.ConversationManager;
import net.didactylos.helpline.data.User;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.didactylos.helpline.stripes.security.Capabilities;
import net.didactylos.helpline.stripes.security.Secured;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.validation.*;

public class SigninAction extends HelplineActionBean
{
	private static final Log log = Log.getInstance(SigninAction.class);
	
	@Validate(required=true)
	private String username;
	
	@Validate(required=true)
	private String password;
	
	private String targetUrl;

	public String getUsername()
	{
		return username;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	public String getTargetUrl()
	{
		return targetUrl;
	}

	public void setTargetUrl(String targetUrl)
	{
		this.targetUrl = targetUrl;
	}
	
	@DontValidate
	@DefaultHandler
	@Secured(Capabilities.NONE)
	public Resolution view()
	{
		return new ForwardResolution("signin.jspx");
	}

	@Secured(Capabilities.NONE)
	public Resolution signin() {
        		
		User user = (User) getContext().getSession()
			.createQuery("from User as user where user.username = ?")
			.setString(0, username)
			.uniqueResult();

        if ((user == null) || (!user.verifyPassword(password))) {
        	// One error for username OR password failure.
        	
        	// We log failed logins (including the password)
        	log.info("Failed sign in. Username: ", username, " Password: ", password);
        	
            ValidationError error = new LocalizableError("signinFailure");
            getContext().getValidationErrors().addGlobalError(error);
            return getContext().getSourcePageResolution();
        }
        else if (!user.hasCapability(Capabilities.SIGN_IN.capabilities()))
        {
            ValidationError error = new LocalizableError("signinDisabled");
            getContext().getValidationErrors().addGlobalError(error);
            return getContext().getSourcePageResolution();
        }
        else
        {
            getContext().setUser(user);
            if (targetUrl != null) {
                return new RedirectResolution(targetUrl);
            }
            else {
                return new RedirectResolution("/");
            }
        }
	}

}
